import 'package:flustars/flustars.dart';
import 'package:flutter/cupertino.dart';
import 'package:osc/utils/string_util.dart';

class RecentTopicData{

  factory RecentTopicData() => getInstance();

  static RecentTopicData _instance;

  RecentTopicData._internal(){
    _init();
  }
  static RecentTopicData getInstance(){
    if(_instance == null){
      _instance = RecentTopicData._internal();
    }
    return _instance;
  }


  final String keyRecentTopic = "recent_topic";
  final String keyRecommendTopicList = "keyRecommendTopicList";
  List<String> recentTopicList;
  List<String> recommendList;
  _init(){
    recentTopicList = SpUtil.getStringList(keyRecentTopic);
    if(recentTopicList == null || recentTopicList.isEmpty){
      recentTopicList = List<String>();
    }
    recommendList = SpUtil.getStringList(keyRecommendTopicList, defValue: List<String>());
  }

  List<String> getRecommendList(){
    return recommendList;
  }

  setRecommendList(List<String> list){
    if(list != null && list.isNotEmpty){
      _saveList(keyRecommendTopicList, list);
    }
  }

  List<String> getRecentTopicList(){
    return recentTopicList;
  }

  addRecentTopic({@required String title}){
    if(StringUtil.isEmpty(title)){
      return;
    }
    if(recentTopicList.contains(title)){
      recentTopicList.remove(title);
      recentTopicList.insert(0, title);
    } else {
      if(recentTopicList.length >= 10){
        recentTopicList.removeLast();
      }
      recentTopicList.insert(0, title);
    }
    _saveList(keyRecentTopic, recentTopicList);
  }

  removeRecentTopic({@required String title}){
    if(StringUtil.isEmpty(title)){
      return;
    }
    if(recentTopicList.contains(title)){
      recentTopicList.remove(title);
    }
    _saveList(keyRecentTopic, recentTopicList);
  }

  clearRecentTopic(){
    recentTopicList.clear();
    SpUtil.remove(keyRecentTopic);
  }

  _add2List(String title, String key, List<String> list){
    if(StringUtil.isEmpty(title)){
      return;
    }
    if(list.contains(title)){
      list.remove(title);
      list.insert(0, title);
    } else {
      list.insert(0, title);
    }
    _saveList(key, list);
  }

  _removeFromList(String title, String key, List<String> list){
    if(StringUtil.isEmpty(title)){
      return;
    }
    if(list.contains(title)){
      list.remove(title);
    }
    _saveList(key, list);
  }

  _clear(String key, List<String> list){
    list.clear();
    SpUtil.remove(key);
  }

  _saveList(String key, List<String> list){
    SpUtil.putStringList(key, list);
  }
}